<?php
class PostsController extends AppController {

	var $name = 'Posts';
	var $helpers = array('Html', 'Form');
	
	function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->deny('add', 'edit', 'delete');
	}
	
	function isOwner( $post_id=NULL ){
		if($this->Auth->user('group_id')==1){
			return true;
		}
		
		if($this->Post->hasAny(
			array(
				'Post.id'=>$post_id, 
				'Post.user_id'=>$this->Auth->user('id')
			)
		)){
			return true;
		} else {
			return false;	
		}
	}

	function add() {
		if (!empty($this->data)) {
			$this->data['Post']['ptime']=time();
			$this->Post->create();
			if ($this->Post->save($this->data)) {
				$this->Session->setFlash(__('The Post has been saved', true));
				$this->redirect($this->Session->read('History.Pre'));
			} else {
				$this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
			}
		}
		$users = $this->Post->User->find('list');
		$this->set(compact('users'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Post', true));
			$this->redirect($this->Session->read('History.Pre'));
		}
		if (!empty($this->data)) {
			if ($this->Post->save($this->data)) {
				$this->Session->setFlash(__('The Post has been saved', true));
				$this->redirect($this->Session->read('History.Pre'));
			} else {
				$this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Post->read(null, $id);
		}
		$users = $this->Post->User->find('list');
		$this->set(compact('users'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Post', true));
			$this->redirect($this->Session->read('History.Pre'));
		}
		if ($this->Post->del($id)) {
			$this->Session->setFlash(__('Post deleted', true));
			$this->redirect($this->Session->read('History.Pre'));
		}
	}

}
?>